<template>
	<view class="content">
		<!-- 	<view class="btns">
			<view @click="back">取 消</view>
			<view @click="getCurrentLocation">获取当前地址</view>
		</view> -->
		<view class="inputCon">
			<view class="searchView">
				<text class="iconfont icon-sousuo"  @click="searchFn"></text>
				<input type="text" placeholder="搜索地点" v-model="searchWords" confirm-type="search" @confirm="searchFn" />
				<text @click="cancel">取消</text>
			</view>
		</view>
		<!-- 地图部分 -->
		<view class="content-map">
			<map id="myMap" style="width: 100%;height: 100%;" v-if="mapFlafg" :latitude="latitude" :longitude="longitude" :markers="markers"
				@tap="tap"  :scale="16"  :title="title"/>
		</view>
		<!-- <view id="container"></view> -->
		<!--  搜索框 -->
 
		<!--  地点列表部分 -->
		<view class="list">
			<view class="item" v-for="(add,index) in dataTips" :key="add.id" 
				:class="selectIndex==index?'active':''" style="position: relative;">
				<view class="info" @click="select(add,index)">
				<view class="name">{{add.name}}</view>
				<view class="address">{{add.district || ''}}{{add.address || ''}}</view>
				</view>
				 <span class="navigate-button" style="width: 50px; height: 30px; font-size: 14px;color: blue;" @click="navigation(index,add)">导航</span>

			</view>
		</view>
		<view style="background-color: aliceblue;"> <image src="../../../static/定位.png" style="width: 38px; height: 38px; z-index: 100000;position: fixed;top:60px;right: 10px;" @click="currentPosition"></image></view>
	</view>
</template>
<script >
	// 引入高德地图api提供的微信小程序的接口
	import amapFile from '@/util/amap-wx.130.js';
	// 创建地图
	var myAmapFun = new amapFile.AMapWX({
		key: '130d6a5be0a5351003b84750814c1abe'
	}); //key值要申请为 去高德地图申请微信小程序的key
	// var myAmapFun = new amapFile.AMapWX({key: ''}); //key我的
	export default {
		data() {
			return {
				mapFlafg:false,
				selectIndex: undefined,
				selectAddr: {},
				searchWords: "",
				id: 1, // 使用 marker点击事件 需要填写id
				title: 'map',
				latitude: 39.91667, // 纬度
				longitude: 116.41667, // 经度
				
				markers: [{
					id:1,
					latitude: 39.91667, // 纬度
					longitude: 116.41667, // 经度
					width: 30,
					height: 30,
					iconPath: ''
					// iconPath: '../../static/ditu.png'
				},
				{
					id:2,
					latitude: 31.2304, // 第二个标记点的纬度（示例值，请替换为实际值）
					longitude: 121.4737, // 第二个标记点的经度（示例值，请替换为实际值）
					width: 30,
					height: 30,
					iconPath: ''
					// iconPath: '../../static/ditu.png'
				}],
				dataTips: []
			}
		},
		onLoad(options) {
			this.mapContext = wx.createMapContext('myMap');
			var self = this;
			self.searchWords=options.address;
			self.latitudeId=options.latitudeId;
			// 使用逗号作为分隔符来分割字符串
			let parts = self.latitudeId.split(",");
			 console.log(self.latitudeId);
			// 现在 parts 是一个数组，包含 ["122", "2321"]
			// 你可以将这两个部分转换成数字并赋值给相应的变量
			let longitude = parseFloat(parts[0]);
			let latitude = parseFloat(parts[1]);
			uni.getLocation({
				type: 'gcj02',
				success: function(res) {
					console.log(res, '当前地址定位');
					if (res.errMsg == "getLocation:ok") {
						console.log(self.mark, 'onload里面看看');
						self.longitude = res.longitude;
						self.latitude = res.latitude;
						self.$set(self.markers[1],"longitude",res.longitude);
						self.$set(self.markers[1],"latitude",res.latitude);
						self.mapFlafg=true;
						console.log(self.markers,"markers")
						self.markers[1].longitude = res.longitude;
						self.markers[1].latitude = res.latitude;
						if(longitude !=NaN ||latitude!=NaN){
							self.getAddressByLatLng(longitude,latitude);
							console.log(longitude,latitude)
						}
						
						self.markers[0].longitude=longitude;
						self.markers[0].latitude=latitude;
						this.searchFn()
						 // 计算中心点
						//  const centerLatitude = (self.markers[0].latitude + self.markers[1].latitude) / 2;
						//  const centerLongitude = (self.markers[0].longitude + self.markers[1].longitude) / 2;
						
						//  // 设置地图的中心点和缩放级别（这里需要根据你的实际需求调整缩放级别）
						//  self.mapContext.moveToLocation({
						//    latitude: centerLatitude,
						//    longitude: centerLongitude,
						//    scale: 14, // 缩放级别，可以根据需要调整
						//  });
						 
						//       // 更新数据中的标记点
						// self.markers = self.markers;
					 // // 设置地图的中心点
					 //            self.mapContext.setCenterLocation({
					 //                latitude: centerLatitude,
					 //                longitude: centerLongitude
					 //            });
					 
					 //            // 设置缩放级别
					 //            self.mapContext.setScale({
					 //                scale: 14, // 根据需要调整缩放级别
					 //            });
					}
				},
				complete: () => {
					// 获取当前位置的地点列表
					myAmapFun.getPoiAround({
						location: self.longitude + ',' + self.latitude,
						success: (data) => {
							console.log("获取当前的列表", data);
							// this.dataTips = data.poisData;
						},
						fail: (info) => {
							console.log(info, '点击地图错误信息1')
						}
					})
			 	},
			});
			this.searchFn()
		},
		methods: {
			
			 getDistance(la1, lo1, la2, lo2) {  // 当前的纬度，当前的经度，接口拿到的纬度，接口拿到的经度
			         let La1 = la1 * Math.PI / 180.0;
			         let La2 = la2 * Math.PI / 180.0;
			         let La3 = La1 - La2;
			         let Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;
			         let distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)));
			         distance = distance * 6378.137;
			         distance = Math.round(distance * 10000) / 10000;
			         return distance;
			       },
	
			getAddressByLatLng(latitude, longitude) {
					    myAmapFun.getRegeo({
					        location: latitude + ',' + longitude,
					        success: (data) => {
					            if (data[0].regeocodeData && data[0].regeocodeData.formatted_address) {
					                console.log('查询到的地址:', data[0].regeocodeData.formatted_address);
									this.searchWords=data[0].regeocodeData.formatted_address
									this.searchFn()
					            } else {
					                console.error('逆地理编码失败，未获取到有效地址信息', data);
					            }
					        },
					        fail: (info) => {
					            console.error('逆地理编码调用失败', info);
					        }
					    });
			    },
			currentPosition(){
				this.mapContext = wx.createMapContext('myMap');
				var self = this;
				uni.getLocation({
					type: 'gcj02',
					success: function(res) {
						console.log(res, '当前地址定位');
						 const latitude = res.latitude; // 纬度
						    const longitude = res.longitude; // 经度
						 //    console.log('当前位置的纬度：', latitude);
						 //    console.log('当前位置的经度：', longitude)
							
							// const distance = self.getDistance(latitude, longitude, latitude, longitude+3);
							// console.log('距离：', Number(distance).toFixed(2) , '米');
							
						if (res.errMsg == "getLocation:ok") {
							console.log(self.mark, 'onload里面看看');
							self.longitude = res.longitude;
							self.latitude = res.latitude;
							self.$set(self.markers[1],"longitude",res.longitude);
							self.$set(self.markers[1],"latitude",res.latitude);
							self.mapFlafg=true;
							console.log(self.markers,"markers")
							self.markers[1].longitude = res.longitude;
							self.markers[1].latitude = res.latitude;
						
						}
					},
					complete: () => {
						// 获取当前位置的地点列表
						myAmapFun.getPoiAround({
							location: self.longitude + ',' + self.latitude,
							success: (data) => {
								console.log("获取当前的列表", data);
								// this.dataTips = data.poisData;
							},
							fail: (info) => {
								console.log(info, '点击地图错误信息1')
							}
						})
				 	},
				});
			},
			navigation(index,add){
				this.select(add, index);
				 wx.openLocation({
				        latitude: this.latitude * 1,
				        longitude: this.longitude * 1,
				        scale: 16, // 缩放比例
				        name: add.name,
				        address: '', // 这个可能会影响地图的定位，所以可以选择不填
				        success(data) {
				          console.log(data)
				        },
				        fail(err) {
				          console.log(err)
				        }
				      })
				},
			cancel() {
				if (this.searchWords) {
					this.searchWords = "";
					myAmapFun.getPoiAround({
						location: this.markers[0].longitude + ',' + this.markers[0].latitude,
						success: (data) => {
							console.log("获取当前的列表", data);
							this.$nextTick(() => {
								this.dataTips = data.poisData;
							})
						},
						fail: (info) => {
							console.log(info)
						}
					})
				}
			},
			reserGeo() {
				myAmapFun.getRegeo({
					success: (data) => {
						console.log("getRegeo", data);
					},
					fail: (info) => {
						console.log(info)
					}
				})
			},
			// 根据地址列表中选择某一个地点
			select(add, index) {
				if (!add) {
					return;
				}
				this.selectIndex = index;
				var location = add.location.split(",");
				console.log(location, add, '列表地点的经纬度');
				this.selectAddr = {
					address: add.pname ? (add.pname + add.cityname + add.adname) : (add.district + add
						.address),
					detailAddress: add.address,
					latitude: location[1],
					longitude: location[0]
				};
				this.markers[0].latitude = +location[1];
				this.markers[0].longitude = +location[0];
				this.setLocation(this.markers[0].longitude,this.markers[0].latitude);
				uni.setStorageSync("address", this.selectAddr.address);
	// 			// 选择地点后，将选取的地点传递到前一个页面中
	// 			var pages = getCurrentPages(); // 获取所有的页面栈
	// 			var prevPage = pages[pages.length - 1]; // 找到上一个页面，注意是页面，如果是页面中有组件，则需要通过页面接受到数据后，再次往组件中传递
	// 			prevPage.$vm.userAddress.locationAddress = this.selectAddr.address; //在上一个页面中就可以用userAddress进行接收
	// 			prevPage.$vm.userAddress.detail = this.selectAddr.detailAddress; //在上一个页面中就可以用userAddress进行接收
	// 			prevPage.$vm.selectAddr = this.selectAddr;
	// 			prevPage.$vm.address = {
	// 				province: add.pname,
	// 				city: add.cityname,
	// 				district: add.adname,
	// 			}
	// 			uni.navigateBack({
	// 				delta: 1
	// 			});
 
			},
			setLocation(lng, lat) {
			      this.longitude = lng;
			      this.latitude = lat;
			      // 你可以在这里更新 markers 数组以显示标记点
			    },
			// 在地图上点击进行选点，这个选点在地图缩放比例较大时无效，因为精读的问题。
			tap(e) {
				console.log(e, '点击了地图');
				var location = e.detail.longitude + ',' + e.detail.latitude
				myAmapFun.getRegeo({
					location: location,
					success: (data) => {
						console.log("获取指定定位信息", data);
						this.selectAddr = {
							address: data[0].regeocodeData.formatted_address,
							latitude: e.detail.latitude,
							longitude: e.detail.longitude
						};
						this.markers[0].latitude = data[0].latitude;
						this.markers[0].longitude = data[0].longitude;
						myAmapFun.getPoiAround({
							location: data[0].longitude + ',' + data[0].latitude,
							success: (data) => {
								console.log("获取当前的列表", data);
								this.dataTips = data.poisData;
							},
							fail: (info) => {
								console.log(info, '点击地图错误信息1')
							}
						})
					},
					fail: (info) => {
						console.log(info, '点击地图错误信息2');
					}
				})
			},
			// 根据内容进行检索
			searchFn() {
				console.log("根据地址检索", this.searchWords);
				myAmapFun.getInputtips({
					keywords: this.searchWords,
					location: '',
					success: (data) => {
						console.log(111, data);
						if (data && data.tips) {
							this.dataTips = data.tips;
							console.log(this.dataTips[0].location)
							if(this.dataTips[0].location.length>0){
								let parts=this.dataTips[0].location.split(",")
								this.markers[0].longitude = parts[0];
								this.markers[0].latitude = parts[1];
								this.setLocation(parts[0],parts[1]);
							}
						}
					},
					fail: data => {
						console.log(222, data);
					}
				})
			},
		}
	}
</script>
 
<style lang="scss" scoped>
	.btns {
 
		position: fixed;
		top: 0;
		left: 0;
		height: 260upx;
		width: 100%;
		background: linear-gradient(to bottom, rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0));
		display: flex;
		align-items: center;
		justify-content: space-between;
		z-index: 10 !important;
 
		view {
			border-radius: 10%;
			margin: 100upx 24upx 0;
			font-size: 30upx;
 
			&:first-child {
				color: #fff;
			}
 
			&:last-child {
				width: 100upx;
				height: 60upx;
				line-height: 60upx;
				text-align: center;
				border-radius: 10upx;
				background: #20c295;
				color: #fff;
			}
		}
	}
 
	.content {
		// position: relative;
		height: 100vh;
		display: flex;
		flex-direction: column;
 
		.content-map {
			width: 100%;
			height: 50vh;
		}
 
		.list {
			// flex: 0 1 calc(50vh - 10upx);
			border-radius: 30rpx;
			background-color: #fff;
			// position: absolute;
			// bottom:-660rpx;
			height: calc(50vh - 10upx);
			overflow-y: auto;
			width: 100%;
			margin: 0upx auto 0;
			padding-bottom: 20upx;
 
			.item {
				border-bottom: 2upx solid #f3f3f3;
				padding: 0 30rpx;
 
				&:last-child {
					border: none;
				}
 
				.address {
					font-size: 22upx;
					color: #666;
					margin: 10upx 0;
				}
 
				.name {
					font-size: 30upx;
					color: #333;
					margin-top: 10upx;
				}
 
				&.active {
					.name {
						font-weight: bold;
						color: #E13500;
					}
 
					.address {
						color: #E13500;
					}
				}
			}
		}
 
		.inputCon {
			flex: 0 1 108rpx;
			width: 100%;
			background: #fff;
			// top: -60upx;
			// position: relative;
			z-index: 20;
			// height: 100upx;
			display: flex;
			align-items: center;
			justify-content: center;
 
			.searchView {
				width: 702upx;
				height: 60upx;
				display: flex;
				align-items: center;
				line-height: 60upx;
				border-radius: 40upx;
				padding: 0 30upx;
				box-sizing: border-box;
				background: #f3f3f3;
				font-size: 26upx;
 
				.iconfont {
					color: #666;
					margin-right: 20upx;
				}
 
				input {
					flex: 1;
				}
 
				view {
					flex-shrink: 0;
				}
			}
			
		}
		.navigate-button{
			position: absolute;
			top: 0px; /* 根据需要调整 */
			right: 0px; /* 根据需要调整 */
		}
 
	}
</style>